package com.xing.fruit.dao;


import org.apache.commons.dbcp.BasicDataSource;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

//操作数据库的基本类
public class DatabaseDao {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    private static BasicDataSource ds;

    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    static{
        try {
            Properties ps = new Properties();
            ps.load(DatabaseDao.class.getClassLoader().getResourceAsStream("db.properties"));
            driver = ps.getProperty("driver");
            url = ps.getProperty("url");
            username = ps.getProperty("username");
            password = ps.getProperty("password");

            ds = new BasicDataSource();
            ds.setDriverClassName(driver);
            ds.setUrl(url);
            ds.setUsername(username);
            ds.setPassword(password);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //1.加载驱动2.获取连接
    public static Connection getConnection() throws SQLException, ClassNotFoundException {
        return ds.getConnection();
    }

    //查询
    public ResultSet execute(String sql, Object[] objects) throws SQLException, ClassNotFoundException {
        preparedStatement = this.getConnection().prepareStatement(sql);
        if (objects != null) {
            for (int i = 0; i < objects.length; i++) {
                preparedStatement.setObject((i + 1), objects[i]);
            }
        }
        resultSet = preparedStatement.executeQuery();
        return resultSet;
    }
    //增删改
    public int update(String sql,Object[] objects) throws SQLException, ClassNotFoundException {
        int result = 0;
        PreparedStatement preparedStatement = this.getConnection().prepareStatement(sql);
        if (objects != null) {
            for (int i = 0; i < objects.length; i++) {
                preparedStatement.setObject((i + 1), objects[i]);
            }
        }
        result= preparedStatement.executeUpdate();
        return result;
    }
    //释放资源
    public void closeAll(){
        try {
            if (resultSet != null){
                resultSet.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (preparedStatement != null) {
                preparedStatement.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
